package com.example.ctrip.plugs;

import com.alibaba.fastjson.JSONObject;
import com.example.ctrip.utils.ImageUtil;
import com.example.ctrip.utils.OpenCvUtil;
import com.example.ctrip.utils.SeleniumUtil;
import com.example.ctrip.commons.Commons;
import com.example.ctrip.entity.StepReturn;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.io.File;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static com.example.ctrip.commons.CommWebTools.isJudgingElement;
import static com.example.ctrip.commons.CommWebTools.isJudgingElements;

public class queryFlight {
    WebDriver webDriver;

    JSONObject paramJson;
    String username;
    String password;
    String airCode;
    String depDate;
    String cabinCode;
    String hd_zcw;
    String depCity;
    String arrCity;

    public queryFlight(Map<String, String> map, WebDriver _webDriver) {
        webDriver = _webDriver;
        paramJson = JSONObject.parseObject(map.get("DETAILS"));
        username = map.get("username");
        password = map.get("password");
        airCode = paramJson.getString("airCode");
        depDate = paramJson.getString("depDate");
        cabinCode = paramJson.getString("cabinCode") + "舱";
        hd_zcw = paramJson.getString("hd_zcw") + "舱";
        depCity = paramJson.getString("depCity");
        arrCity = paramJson.getString("arrCity");

//        airCode = map2.get("airCode");
//        depDate = map2.get("depDate");
//        cabinCode = map2.get("cabinCode") + "舱";
//        hd_zcw = map2.get("hd_zcw") + "舱";
    }

    public StepReturn Step0() {
        //登录，输入用户名密码，且点击登录按钮
        try {
            if (webDriver.getCurrentUrl().equals("https://www.chinaexpressair.com/yss/login/")) {
                if (!isJudgingElement(webDriver, By.id("pwdLoginUsername"))) {
                    return new StepReturn(0);
                }
                webDriver.findElement(By.id("pwdLoginUsername")).sendKeys(username);
                webDriver.findElement(By.id("pwdLoginPassword")).sendKeys(password);
                Thread.sleep(2000);
                webDriver.findElement(By.id("pwdLoginBtn")).click();
            }
        } catch (Exception e) {
            return new StepReturn(0);
        }
        return new StepReturn(1);
    }

    public StepReturn Step1() {
        //破解云盾
        int tryTimes = 0;
        try {
            int loginTimes = 0;
            while (true) {
                Thread.sleep(3500);
                String url;
                String url1;
                System.out.println(webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src"));
                url = webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src");
                url1 = webDriver.findElement(By.className("yidun_jigsaw")).getAttribute("src");
                while (url == null || url1 == null) {
                    Thread.sleep(500);
                    url = webDriver.findElement(By.className("yidun_bg-img")).getAttribute("src");
                    url1 = webDriver.findElement(By.className("yidun_jigsaw")).getAttribute("src");
                    tryTimes++;
                    if (tryTimes > 50) {
                        //50次都找不到，则要重新刷新页面
                        return new StepReturn(0);
                    }
                }
                //下载并copy图片
                String[] split = url.split("/");
                String fileName = split[split.length - 1];
                File file = new File(Commons.getIMGCODE() + fileName);
                InputStream inputStream = ImageUtil.getInputStreamByGet(url);
                ImageUtil.saveData(inputStream, file);
                ImageUtil.convert(Commons.getIMGCODE() + fileName, "png", Commons.getIMGCODE() + "one.png");

                String[] split1 = url1.split("/");
                String fileName1 = split1[split1.length - 1];
                File file1 = new File(Commons.getIMGCODE() + fileName1);
                InputStream inputStream1 = ImageUtil.getInputStreamByGet(url1);
                ImageUtil.saveData(inputStream1, file1);
                ImageUtil.convert(Commons.getIMGCODE() + fileName1, "png", Commons.getIMGCODE() + "two.png");

                double distance = OpenCvUtil.getDistance("file:///" + Commons.getIMGCODE() + "one.png", "file:///" + Commons.getIMGCODE() + "two.png");
                SeleniumUtil.move(webDriver, webDriver.findElement(By.className("yidun_jigsaw")), (int) distance + 18);

                new File(Commons.getIMGCODE() + "one.png").delete();
                new File(Commons.getIMGCODE() + "two.png").delete();
                file.delete();
                file1.delete();
                Thread.sleep(2000);

                if (!isJudgingElement(webDriver, By.className("yidun_bg-img"))) {
                    //如果yidun背景没有了，证明又没通过验证，又没验证码出现，需要再次点击一下登录按钮
                    webDriver.findElement(By.id("pwdLoginBtn")).click();
                    if (loginTimes++ > 30) {
                        //30次都没拼正确，则要重新刷新页面
                        return new StepReturn(0);
                    }
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            if (!isJudgingElement(webDriver, By.className("yidun_bg-img"))) {
                return new StepReturn(1);
            }
            return Step1();
        }
    }

    public StepReturn Step2() {
        //查询航班
        JSONObject jsonObject = null;
        webDriver.get("https://www.chinaexpressair.com/yss/flight-search/bookingOneTrip");
        //查询航班
        try {
            /**
             * 登陆完毕，接着处理后续任务
             */
            if (isJudgingElements(webDriver, By.className("datepicker"))) {
                ((JavascriptExecutor) webDriver).executeScript("document.getElementById(\"cityBegin\").setAttribute(\"threecode\",\"" + depCity + "\")");
                ((JavascriptExecutor) webDriver).executeScript("document.getElementById(\"cityEnd\").setAttribute(\"threecode\",\"" + arrCity + "\")");
                ((JavascriptExecutor) webDriver).executeScript("document.getElementsByClassName(\"datepicker\")[0].removeAttribute(\"readonly\")");
                ((JavascriptExecutor) webDriver).executeScript("Object.defineProperties(navigator,{ webdriver:{ get: () => false } })");
                Thread.sleep(1000);
                webDriver.findElement(By.className("datepicker")).clear();
                Thread.sleep(1000);
                webDriver.findElement(By.className("datepicker")).sendKeys(depDate);
                webDriver.findElement(By.className("tri-cdtion-btn")).click();
            } else {
                return new StepReturn(0);
            }

            Thread.sleep(1000);
            if (isJudgingElements(webDriver, By.id("nc_1_n1z"))) {
                SeleniumUtil.move(webDriver, webDriver.findElement(By.id("nc_1_n1z")), 300);
            } else {
                return new StepReturn(0);
            }

            List<WebElement> lis = new LinkedList<WebElement>();
            if (isJudgingElements(webDriver, By.className("num"))) {
                lis = webDriver.findElements(By.className("num"));
            } else {
                if (isJudgingElement(webDriver,By.className("noFlight"))){
                    return new StepReturn(3,"未获取到航班信息");
                }
                return new StepReturn(0);
            }

            if (lis.size() == 0) {
                return new StepReturn(3, "无对应航班");
            }
            //遍历航班号定位对应的航班
            Thread.sleep(2000);
            int i;
            boolean isFind = false;
            /**
             * 寻找航班
             */
            for (i = 0; i < lis.size(); i++) {
                if (lis.get(i).getText().equals(airCode)) {
                    isFind = true;
                    break;
                }
            }

            if (!isFind) {
                return new StepReturn(3, "无对应航班");
            }

            //点击对应的订票按钮
            if (isJudgingElements(webDriver, By.className("acas-btn"))) {
                webDriver.findElements(By.className("acas-btn")).get(i).click();
            } else {
                return new StepReturn(3, "无对应航班");
            }

            Thread.sleep(2000);
            //获取每个舱位
            List<WebElement> cabinCodes = new LinkedList<>();
            if (isJudgingElements(webDriver, By.className("cabin"))) {
                cabinCodes = webDriver.findElements(By.className("cabin"));
            } else {
                return new StepReturn(3, "未找到舱位信息");
            }

            /**
             * 寻找舱位
             */
            isFind = false;
            //遍历舱位定位对应的舱位的票
            for (i = 0; i < cabinCodes.size(); i++) {
                System.out.println(cabinCodes.get(i).getText());
                if (cabinCodes.get(i).getText().equals(cabinCode) || cabinCodes.get(i).getText().equals(hd_zcw)) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                return new StepReturn(3, "无对应舱位");
            }

            //如果找到对应机票,点击订票
            List<WebElement> chksel = new LinkedList<>();
            if (isJudgingElements(webDriver, By.className("chk_sel"))) {
                chksel = webDriver.findElements(By.className("chk_sel"));
            } else {
                return new StepReturn(3, "无对应舱位");
            }

            /**
             * 寻找对应机票按钮
             */
            isFind = false;
            for (i = 0; i < chksel.size(); i++) {
                if (chksel.get(i).getText() != null && !chksel.get(i).getText().equals("")) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                return new StepReturn(3, "无对应舱位按钮");
            }
            chksel.get(i).click();

            Thread.sleep(2000);
            //获取票价信息(价格是通过js动态加载的，需要用js或者jquery进行抓取)
            String adultPricee = (String) ((JavascriptExecutor) webDriver).executeScript("return $(\".adult_price\").children(\"em\").text()");
            int adultPrice = Integer.parseInt(adultPricee.substring(1));

            //机建费
            String adultFundd = (String) ((JavascriptExecutor) webDriver).executeScript("return $(\".adult_fund\").children(\"em\").text()");
            int adultFund = Integer.parseInt(adultFundd.substring(1));

            //燃油费
            String adultFueloill = (String) ((JavascriptExecutor) webDriver).executeScript("return $(\".adult_fueloil\").children(\"em\").text()");
            int adultFueloil = Integer.parseInt(adultFueloill.substring(1));

            //查询到需要返回的json
            jsonObject = new JSONObject();
            jsonObject.put("adultPrice", adultPrice);
            jsonObject.put("adultFund", adultFund);
            jsonObject.put("adultFueloil", adultFueloil);
        } catch (Exception e) {
            //刷新页面重试
            return new StepReturn(0);
        }
        return new StepReturn(4, jsonObject);
    }
}
